
<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">基础管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/' }">商品管理</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 搜索筛选 -->
        <el-form :inline="true" :model="goods" class="user-search">  
            <el-form-item label="商品类别">
                <el-select v-model="goods.classs" filterable placeholder="请选择">
                    <el-option
                    v-for="item in classList"
                    :key="item.goods_class_id"
                    :label="item.goods_class_name"
                    :value="item.goods_class_id">
                    </el-option>
                </el-select>
                <!-- <el-input size="small" v-model="goods.class" placeholder="输入商品名称"></el-input> -->
            </el-form-item>
            <el-form-item label="商品名称">
                <el-select v-model="goods.names" filterable placeholder="请选择">
                     <el-option
                    v-for="item in dataStore"
                    :key="item.goods_id"
                    :label="item.goods_name"
                    :value="item.goods_id">
                    </el-option>
                </el-select>
                <!-- <el-input size="small" v-model="goods.num" placeholder="输入商品类别"></el-input> -->
            </el-form-item>
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-refresh" @click="reSeach">重置</el-button>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandleEdit">添加</el-button>
            </el-form-item>
        </el-form>
       <!--列表-->
        <el-table size="small" height="400px" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
             <!-- <el-table-column sortable prop="merchant_name" label="餐厅名" width="150">
            </el-table-column> -->
            <el-table-column sortable prop="goods_name" label="商品名称" width="150" />
            <el-table-column sortable prop="goods_img" label="图片" width="150" >
                 <template slot-scope="scope">
                     <el-image
                     v-if="scope.row.goods_img"
                    style="width: 50px; height: 50px"
                    :src="scope.row.goods_img"
                    fit="fill" lazy />
                 </template>
            </el-table-column>
            <el-table-column sortable prop="goods_price" label="价格" width="150">
            </el-table-column>
            <el-table-column sortable prop="goods_class_name" label="类型" width="150">
            </el-table-column>
             <el-table-column sortable prop="goods_detail" label="商品描述" width="250">
            </el-table-column>
             <!-- <el-table-column sortable prop="goods_img" label="图片" width="250">
            </el-table-column> -->
            <el-table-column align="center" label="操作" min-width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger"  plain @click="deleteUser(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
         <!-- 分页组件 -->
        <el-pagination class="page-box" 
            @size-change="handleSizeChange" 
            @current-change="handleCurrentChange" 
            background 
            :current-page="currentPage" 
            :page-size="pageSize" 
            :total="total">
        </el-pagination>
        <!-- 编辑界面 -->
        <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click="closeDialog1">
            <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
                <!-- <el-form-item label="商家名称" prop="merchant_id">  
               
                    <el-select v-model="editForm.merchant_id" filterable placeholder="请选择">
                        <el-option
                            v-for="item in merchantList"
                            :key="item.merchant_id"
                            :label="item.merchant_name"
                            :value="item.merchant_id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="类型" prop="goods_class_id">
                     <el-select v-model="editForm.goods_class_id" filterable placeholder="请选择">
                        <el-option
                            v-for="item in classList"
                            :key="item.goods_class_id"
                            :label="item.goods_class_name"
                            :value="item.goods_class_id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="名称" prop="goods_name">
                    <el-input size="small" v-model="editForm.goods_name" auto-complete="off" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                 <el-form-item label="图片" prop="goods_img">
                      <el-upload
                            class="upload-demo"
                            ref="upload"
                            action="http://localhost:3000/friends/ictures/"
                            :http-request="picUpload"
                            :on-success="handleSuccess"
                            :file-list="fileList"
                            :auto-upload="true" >
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">
                            上传到服务器
                        </el-button> -->
            </el-upload>
                </el-form-item>
                <el-form-item label="价格" prop="goods_price">
                    <el-input-number v-model="editForm.goods_price" :min="0.01"  label="描述文字"></el-input-number>
                </el-form-item>
                 <el-form-item label="描述" prop="goods_detail">
                    <el-input size="small" v-model="editForm.goods_detail" auto-complete="off" placeholder="请输入商品描述"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog2">取消</el-button>
                <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import axios from "axios"
import { newStampChangeFormat } from "./../../untils/index"
import { mapState } from 'vuex';
export default {
    // 默认子路由 不能有name属性
    name: "Goods",
    data() {
        return {
            fileList: [],
            imageUrl: '', // 用于保存上传后的图片 URL  
            loading: false, //是显示加载,
            pageSize: 7,   //每页显示的条目个数
            currentPage: 1,  //当前页,
            total: 2,  //总条数
            editFormVisible: false, //控制编辑页面显示与隐藏
            dist: "", //区别唯一标识符  add 添加  del删除  edit编辑
            distNum: "",  //编辑的第几条数据
            classList: [],  //类型列表
            merchantList: [],  //商家列表
            goods: {
                names: "",
                classs: "",
            },
            listData: [ 
                {
                    deptName: "商品名称1",
                    deptNo: "商品代码1",
                    editTime: "修改时间1",
                    editUser: "修改人1"
                }
            ],
            editForm: {
                goods_id: '',
                merchant_id: this.user_id,
                goods_name: '',
                goods_img: '',
                goods_price: '',
                goods_class_id: '',
                goods_detail: '',
            },
            title: '添加',
            rules: {
                merchant_id: [{ required: true, message: '请选择商户', trigger: 'blur' }],
                goods_class_id: [{ required: true, message: '请输入类型', trigger: 'blur' }],
                goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
                goods_price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
                goods_detail: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]

            },
            searchArr: [],
            dataStore: [],  //存储旧的数据
            users: "",
            role: '',
        }
    },
    computed: {  
  
  },  
    methods: {
        handleSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        submitUpload() {
            this.$refs.upload.submit();
            this.fileList = [];
        },
        picUpload(f) {
            let params = new FormData()
            //注意
            params.append("file", f.file);
            axios({
                method: 'post',
                url: '/friends/ictures',
                data: params,
                headers: {
                    'content-type': 'multipart/form-data'
                }
            }).then(resp => {
                //这里返回的是头像的url
                console.log(resp.data.names);
                this.imageUrl =  'http://localhost:3000' + "/uploads/" + resp.data.names;
            })
        }, 
        search() {
            if (!this.goods.names && !this.goods.classs) {
                return;
            }
            //条件查询
             axios.get("/goods/lists/ifs", {
                 params: {
                     goods_id: this.goods.names,
                     goods_class_id: this.goods.classs,
                 }
             })
            .then(
                res => {
                    this.dataStore = res.data.data;
                    // this.listData = res.data.data;
                    this.handleCurrentChange(1); 
                    this.total = res.data.data.length;
                    // console.log(res.data.data)
                }
            )
           
            //每次搜索前将旧的数据恢复
            // this.listData = this.dataStore;
            // this.handleCurrentChange(1);
            //根据商品代码或者商品名称检索 满足其中一个即可
            // let deptName = this.goods.names;
            // let deptNo = this.goods.num;
            // //
            // if(deptName == '' && deptNo == '') {
            //     // this.listData = this.dataStore;
            //      this.handleCurrentChange(1);
            //      this.total = this.dataStore.length;
            //     return;
            // }
            
            // let newArr = [];
            // let reg = new RegExp(deptName);
            
            // this.dataStore.forEach((elem, index) => {
            //     if (deptName == elem.deptName || deptNo == elem.deptNo) newArr.push(elem)
            //     if(deptName == '') {
            //         if (deptNo == elem.deptNo) newArr.push(elem)
            //     } else
            //      if(reg.test(elem.deptName) || deptNo == elem.deptNo) {
            //         newArr.push(elem)
            //     }
            // })
            // this.listData = newArr;
            // this.total = newArr.length;
        },
        //重置
        reSeach() {
            this.goods.names = '';
            this.goods.classs = '';
            this.getList();
               
            
        },
        //add
        addHandleEdit() {
            //清空数据
            this.clearData();
            this.title = "添加";
            this.dist = "add";
            this.editFormVisible = true;
            

        },
        // 修改
        handleEdit(index, row) {
            this.title = '修改';
            this.dist = "edit";
            this.distNum = index;
            this.editFormVisible = true;
            

            //数据渲染到dialog
            this.editForm.goods_id = row.goods_id;
            this.editForm.merchant_id =   row.merchant_id; 
            this.editForm.goods_name =    row.goods_name;
            this.editForm.goods_img =    row.goods_img;
            this.editForm.goods_price =   row.goods_price;
            this.editForm.goods_class_id =row.goods_class_id;
            this.editForm.goods_detail =  row.goods_detail;
            this.imageUrl =  row.goods_img;
            

        },
        handleSizeChange(val) {
           this.pageSize = val;
        //    console.log('handleSizeChange',val)

        },
        handleCurrentChange(val) {
            this.currentPage = val;
            let pageSize = this.pageSize;
            let da = this.dataStore;
            let i = (val - 1) * pageSize;
            let arr = da.slice(i , i + pageSize);
            this.listData = arr;
        },
        //提交保存
        submitForm(editData) {
            this.$refs[editData].validate(valid => {
                if (valid) {
                    this.editForm.goods_img = this.imageUrl;
                    console.log(this.imageUrl);
                    if (this.dist == "add") {
                        
                        axios.post('/goods/add', {
                            data: this.editForm
                        }).then(
                            res => {
                               if(res.data.data = true) {
                                   this.$message({
                                        message: '添加成功',
                                        type: 'success'
                                    });
                                    this.getList();
                               } else {
                                   this.$message.error('添加失败');
                               }
                            }
                        )
                       
                       
                    } else if(this.dist == "edit") {
                        axios.put('/goods/put', {
                            data: this.editForm
                        }).then(res => {
                            if(res.data.data) {
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                this.getList();
                            } else {
                                this.$message.error('修改失败');
                            }
                        })
                        
                        
                    }
                    
                    //清空内容
                    this.clearData();
                    //关闭dialog
                    this.editFormVisible = false;
                    
               


                } else {
                    return false
                }
            })
        },
        //关闭dialog
        closeDialog1() {
            this.editFormVisible = false;
            //数据清空
            this.clearData();
        },
        //关闭dialog
        closeDialog2() {
            this.editFormVisible = false;
            //数据清空
            this.clearData();
        },
        //删除
        deleteUser(index, row) {
            this.dist = "del"
            console.log(index, row);

             this.$confirm('此操作将删除改商品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete('/goods/del', {
                        params : {
                            goods_id: row.goods_id
                        }
                    })
                        .then(res => {
                            console.log(res);
                           if(res.data.data) {
                                   this.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                    this.getList();
                               } else {
                                   this.$message.error('删除失败');
                               }
                        })
           
                  
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                });


            
            // this.$message.error('您所要删除的商品不存在');
        },
        clearData() { 
            this.editForm.goods_id = '';
            this.editForm.merchant_id =  this.user_id;
            this.editForm.goods_name = '';
            this.editForm.goods_img = '';
            this.editForm.goods_price = '';
            this.editForm.goods_class_id = '';
            this.editForm.goods_detail = '';
        },
        getList() {
            let getlocal = localStorage.getItem("localUser");
            this.users = JSON.parse(getlocal).user;
            this.role = JSON.parse(getlocal).role;
            this.user_id = JSON.parse(getlocal).user_id;
             axios.get("/goods/lists", {
                 params: {
                     user_id: this.user_id
                 }
             })
            .then(
                res => {
                    this.dataStore = res.data.data;
                    // this.listData = res.data.data;
                    this.handleCurrentChange(1); 
                    this.total = res.data.data.length;
                    // console.log(res.data.data)
                }
            )
           
        },
        getClass() {
             axios.get("/goods/mer/list", {
                 params: {
                     user_id: this.user_id
                 }
             })
            .then(
                res => {
                    this.classList = res.data.data;
            })
        },
        // getMerchant() {
        //     axios.get("/merchant/list")
        //         .then(
        //             res => {
        //                 this.merchantList = res.data.data;
        //             }
        //         )
        // }
    },
    created() {
       
       
        this.getList();
         this.getClass();
        // this.getMerchant();
    },
    mounted() {
         
    }
}
</script>

<style scoped>
.el-form {
    margin: 0;
    padding: 0;
    text-align: left;
}
.el-pagination {
    margin-top: 20px;
}
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}

</style>